/* Copyright 2008. All rights reserved. */
package org.bling.parser.tags;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.jexl.Expression;
import org.apache.commons.jexl.ExpressionFactory;
import org.apache.commons.jexl.JexlContext;
import org.apache.commons.jexl.JexlHelper;
import org.bling.parser.BlingParserException;
import org.bling.parser.style.StyleParser;
import org.bling.util.Util;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Widget;

/**
 * renders an SWT Combo Box
 * 
 * @author DISBROB
 * 
 */
public class ComboTag extends Tag {

	protected Combo combo;
	protected String name = "";
	protected String property = "";
	protected String paramProperty = "";
	protected String style = "";
	

	public void setParamProperty(String property) {
		this.paramProperty = property;
	}
	
	public void setProperty(String property) {
		this.property = property;
	}
	
	public void setStyle(String style) {
		this.style = style;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}

	@Override
	public int doStartTag() throws BlingParserException {
		super.doStartTag();

		if (!(parent.getWidget() instanceof Composite)) {
			throw new BlingParserException(
					"Table tags can only be inside of composites");
		}

		Composite composite = (Composite) parent.getWidget();
		combo = new Combo(composite, SWT.READ_ONLY);
		combo.setData(paramProperty);

		StyleParser.applyStyle((Control) getWidget(), style);
		
		return EVAL_PAGE;
	}

	@Override
	public Widget getWidget() throws BlingParserException {
		return combo;
	}

	@Override
	public int doEndTag() throws BlingParserException {

		// Load the array data into the table
		Object obj = context.getAttribute(name);
		if (obj == null) {
			return EVAL_PAGE;
		}
		
		String jexlExp = name;
		if (!Util.isBlankOrNull(property)) {
			jexlExp += "." + property;
		}
		
		List<String> values = new ArrayList<String>();
		
		try {
			Expression e = ExpressionFactory.createExpression(jexlExp);
			JexlContext jc = JexlHelper.createContext();
			
			if (obj instanceof Collection) {
				Iterator iterator = ((Collection) obj).iterator();
				while (iterator.hasNext()) {
					Object item = iterator.next();
					jc.getVars().put(name, item);
					Object value = e.evaluate(jc);
					if (value == null) {
						value = "";
					}
					values.add(value.toString());
				}
			}
		} catch (Exception e) {
			values.add("");
		}

		String[] array = new String[0];
		combo.setItems(values.toArray(array));

		return EVAL_PAGE;
	}

}
